//
//  NewsListViewController.swift
//  puretennis
//
//  Created by Derek Zheng on 1/22/15.
//  Copyright (c) 2015 IYE Technologies. All rights reserved.
//

import Foundation

enum Method: String{
    case NEWEST = "NEWEST";
    case HISTORY = "HISTORY";
}

class NewsListView: UITableView, UITableViewDelegate, UITableViewDataSource{
    
    var newsList:[NSDictionary] = []
    
    var newsListCell:[UITableViewCell] = []
    
    override init() {
        super.init()
        self.delegate = self
        self.dataSource = self
        self.backgroundColor = UIColor.clearColor()
        self.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func reloadData() {
        newsListCell.removeAll()
        var index = 0
        for news in  newsList{
            let cell = self.initiateTableCell(self, news: news, index: index)
            newsListCell.append(cell)
            index++
        }
        super.reloadData()
    }
    
    func setupRefreshGesture(){
        self.addHeaderWithCallback { () -> Void in
            self.loadNews(Method.NEWEST)
            self.headerEndRefreshing()
        }
        
        self.addFooterWithCallback { () -> Void in
            self.loadNews(Method.HISTORY)
            self.footerEndRefreshing()
        }
    }
    
    
    func loadNews(method: Method){
        let key = "_newsList"
        var localList: AnyObject? = Utils.getValue(key)
        
        if(localList != nil){
            newsList = localList as [NSDictionary]
        }
        
        let url = "/api/v1/news/load"
        
        var loadNewest: Bool = Method.NEWEST == method
        var loadHistory: Bool = !loadNewest
        var updateTo: String = ""
        

        var cursor = loadNewest ? newsList.first : newsList.last
        
        if(cursor != nil){
            updateTo = cursor!.objectForKey("createdDateTime") as String
        }
        
        var body = NSMutableDictionary()
        
        body.setValue(loadNewest, forKey: "loadNewest")
        body.setValue(loadHistory, forKey: "loadHistory")
        body.setValue(updateTo, forKey: "updateTo")
        
        var response = HttpUtils.sendSynchronousRequest(url, method: RequestMethod.POST, requestBody: body) as NSDictionary
        
        var list = response.objectForKey("newsList") as [NSDictionary]
        
        if(loadNewest){
            newsList = list + newsList
        }else{
            newsList = newsList + list
        }
        
        Utils.saveData(newsList, key: key)
        
        reloadData()
    }
    
    func initiateTableCell(tableView: UITableView, news: NSDictionary, index: Int) -> UITableViewCell{
        
        var cell =  UITableViewCell()

        cell.backgroundColor = UIColor.clearColor()
        var bg = UIView()
        bg.frame.size.width = tableView.frame.width
        bg.backgroundColor = ViewUtils.colorWithHexString("E0EFFC").colorWithAlphaComponent(0.5)

        bg.layer.cornerRadius = 5
        cell.addSubview(bg)

        
        var titleLabel = UITextView()
        
        titleLabel.editable = false
        titleLabel.scrollEnabled = false

        
        titleLabel.backgroundColor = UIColor.clearColor()
        titleLabel.frame.size.width = tableView.frame.width

        titleLabel.textAlignment = NSTextAlignment.Left;
        titleLabel.textColor = UIColor.blackColor();
        titleLabel.font = Utils.systemFont(16)
        titleLabel.text = (newsList[index].objectForKey("title") as String)
        
        
        titleLabel.sizeToFit()
        
        bg.addSubview(titleLabel)

        var dateLabel = UITextView()
        dateLabel.editable = false
        dateLabel.scrollEnabled = false
        dateLabel.textAlignment = NSTextAlignment.Left;
        dateLabel.backgroundColor = UIColor.clearColor()
        dateLabel.text = (news.objectForKey("createdDateTime") as String)
        dateLabel.frame.origin.x = titleLabel.frame.origin.x
        dateLabel.frame.origin.y = titleLabel.frame.origin.y + titleLabel.frame.height + 2
        dateLabel.font = Utils.systemFont(10)
        dateLabel.sizeToFit()
        bg.addSubview(dateLabel)
        
        if(titleLabel.frame.height > cell.frame.height){
            cell.frame.size.height = titleLabel.frame.height
        }
        cell.frame.size.height += dateLabel.frame.height
        
        bg.frame.size.height = cell.frame.height - 3
        return cell
    }
    
    
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        var cell = self.newsListCell[indexPath.row]
        return cell.frame.height
    }

    func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool{
        return false
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return newsList.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        var index = indexPath.row
        
        return newsListCell[index]
    }

}